package com.cssw.fyzb.busi.api.user;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.core.model.vo.user.DistrictTreeNodeVo;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.simplecache.SimpleCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.cssw.fyzb.busi.cache.CacheKeys.districtTree;

@Function(description = "省市区")
@Component
public class GetDistrictTree implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleCache simpleCache;

    @Override
    public Response execute(Request request) throws Exception {
        //取缓存
        String cacheTree = simpleCache.get(districtTree());
        List<DistrictTreeNodeVo> tree = null;
        //缓存为空，直接去数据库拿数据
        if (StringUtil.isEmpty(cacheTree)) {
            tree = userService.getDistrictTree();
            simpleCache.put(districtTree(), JSON.toJSONString(tree), true);
        } else {
            tree = JSON.parseArray(cacheTree, DistrictTreeNodeVo.class);
        }

        return Response.success().put("list", tree);
    }
}
